package com.ler.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.ler.yrmall.basic.Result;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 演示环境拦截器
 * @author leron
 */
@Component
public class DemoEnvironmentFilter implements GlobalFilter, Ordered {

    private static final String[] BLOCKED_URLS = { "/demo-url1", "/demo-url2" };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestUrl = exchange.getRequest().getURI().getPath();

        if (isBlockedUrl(requestUrl)) {
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            Result<?> errorResponse = Result.error(406, "演示环境禁止操作");
            String jsonError = JSON.toJSONString(errorResponse);
            return exchange.getResponse().writeWith(Mono.just(exchange.getResponse()
                    .bufferFactory().wrap(jsonError.getBytes())));
        }

        return chain.filter(exchange);
    }

    private boolean isBlockedUrl(String url) {
        for (String blockedUrl : BLOCKED_URLS) {
            if (url.equals(blockedUrl)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
